const express = require("express");
const SocketServer = require("ws").Server;
const { wlog } = require("./utils");
const PORT = 8000;

const server = express().listen(PORT, () =>
    console.log(`SocketServer Listening on http://localhost:${PORT}`)
);

// 将 express 服务交给 socketServer 开启 webSocket 服务
const wss = new SocketServer({ server });

wss.on("connection", (ws) => {
    wlog("Client connected");
    // wlog('wss::', wss)
    // wlog('wss.clients::', wss.clients) // wss.clients is a set
    ws.on("message", (message) => {
        wlog("服务端收到: %s", message, typeof message, message.toString());
        // ws.send(message) // 直接返回收到的消息
        ws.send(message.toString().split("").reverse().join("")); // 返回 翻转的消息
    });

    ws.on("close", () => wlog("Client disconnected"));

    ws.send("welcome");
});
